using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public float speed = 5f;
    Animator animator;
    Rigidbody2D rb;
    public Vector2 movement;
    SpriteRenderer spriter;
    [NonSerialized]
    public Scanner scanner;
    public RuntimeAnimatorController[] animCon;

    public Hand[] hands;

    private void OnEnable()
    {
        speed *= Character.Speed;
        animator.runtimeAnimatorController = animCon[GameManager.instance.playerId];
    }

    void Awake()
    {
        spriter = GetComponent<SpriteRenderer>();
        animator = GetComponent<Animator>();
        rb = GetComponent<Rigidbody2D>();
        scanner = GetComponent<Scanner>();
        hands = GetComponentsInChildren<Hand>();
    }

    void Update()
    {
        if (!GameManager.instance.isLive) return;

        //获取虚拟摇杆的位置
        float horizontal = GameManager.instance.joystick.Horizontal;
        float vertical = GameManager.instance.joystick.Vertical;
        if (horizontal != 0 || vertical != 0)
        {
            // 获取输入
            movement.x = horizontal;
            movement.y = vertical;
        }
        else
        {
            // 获取输入
            movement.x = Input.GetAxisRaw("Horizontal");
            movement.y = Input.GetAxisRaw("Vertical");
        }


        SetAnimation();
        SetFlip();
    }

    private void FixedUpdate()
    {
        if (!GameManager.instance.isLive) return;
        //移动代码
        rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime);
    }

    //切换动画
    void SetAnimation()
    {

        if (movement != Vector2.zero)
        {
            animator.SetBool("run", true);
        }
        else
        {
            animator.SetBool("run", false);
        }
    }

    //翻面
    void SetFlip()
    {
        //翻面
        if(movement.x>0){
            spriter.flipX = false;
        }
        if(movement.x<0){
            spriter.flipX = true;
        }
    }

    void OnCollisionStay2D(Collision2D collision)
    {
        // 如果玩家已经死亡，则不执行接下来的逻辑
        if (!GameManager.instance.isLive) return;

        // 对玩家的生命值进行递减
        GameManager.instance.health -= Time.deltaTime * 10;

        // 如果玩家生命值小于0，则进行相应处理
        if (GameManager.instance.health < 0)
        {
            // 关闭当前物体所有子对象的渲染
            for (int index = 1; index < transform.childCount; index++)
            {
                transform.GetChild(index).gameObject.SetActive(false);
            }

            // 播放死亡动画
            animator.SetTrigger("Dead");
            GameManager.instance.GameOver();
        }
    }

}
